from flask import Flask, render_template, request, jsonify
import math
import re

app = Flask(__name__)

class Calculator:
    """计算器类，处理各种数学运算"""
    
    @staticmethod
    def evaluate_expression(expression):
        """安全地计算数学表达式"""
        try:
            # 移除空格
            expression = expression.replace(' ', '')
            
            # 检查是否包含非法字符
            if not re.match(r'^[0-9+\-*/().√πe\s]+$', expression):
                return "错误：包含非法字符"
            
            # 替换特殊符号
            expression = expression.replace('π', str(math.pi))
            expression = expression.replace('e', str(math.e))
            expression = expression.replace('√', 'math.sqrt')
            
            # 安全计算
            allowed_names = {
                "__builtins__": {},
                "math": math,
                "abs": abs,
                "round": round,
                "pow": pow,
                "sqrt": math.sqrt,
                "sin": math.sin,
                "cos": math.cos,
                "tan": math.tan,
                "log": math.log,
                "log10": math.log10,
                "exp": math.exp,
                "pi": math.pi,
                "e": math.e
            }
            
            result = eval(expression, allowed_names, {})
            
            # 检查结果是否为数字
            if isinstance(result, (int, float)):
                # 格式化结果
                if isinstance(result, float):
                    if result.is_integer():
                        return str(int(result))
                    else:
                        return f"{result:.10g}"  # 最多10位有效数字
                return str(result)
            else:
                return "错误：无效结果"
                
        except ZeroDivisionError:
            return "错误：除零"
        except ValueError as e:
            return f"错误：数值错误 - {str(e)}"
        except SyntaxError:
            return "错误：语法错误"
        except Exception as e:
            return f"错误：{str(e)}"

calculator = Calculator()

@app.route('/')
def index():
    """主页面"""
    return render_template('calculator.html')

@app.route('/calculate', methods=['POST'])
def calculate():
    """处理计算请求"""
    data = request.get_json()
    expression = data.get('expression', '')
    
    if not expression:
        return jsonify({'success': False, 'error': '表达式为空'})
    
    result = calculator.evaluate_expression(expression)
    
    # 检查是否为错误信息
    if result.startswith('错误：'):
        return jsonify({'success': False, 'error': result})
    else:
        return jsonify({'success': True, 'result': result})

@app.route('/history')
def get_history():
    """获取计算历史（暂时返回空数组，可以后续扩展）"""
    return jsonify({'history': []})

if __name__ == '__main__':
    app.run(debug=True, port=5001)  # 使用5001端口避免与office转pdf应用冲突 